package com.boarsoft.boar.deploy.plan.action;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boarsoft.bean.LogonI;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.app.AppBiz;
import com.boarsoft.boar.deploy.entity.AppDeployInfo;
import com.boarsoft.boar.deploy.entity.BuildPlanItem;
import com.boarsoft.boar.deploy.plan.PlanAppBiz;
import com.boarsoft.common.Authorized;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.web.login.Logined;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@RestController
@RequestMapping("/plan/app")
public class PlanAppAction {
	private static final Logger log = LoggerFactory.getLogger(PlanAppAction.class);

	@Autowired
	private PlanAppBiz planAppBiz;
	@Autowired
	private AppBiz appBiz;

	@RequestMapping("/add.do")
	@Authorized(code = "deploy.plan.item.save")
	public ReplyInfo<Object> save(@Logined LogonI<String> logon, BuildPlanItem o, String targetIds) {
		for (String targetId : targetIds.split(",")) {
			log.info("Add app item {} to build plan {}", targetId, o.getPlanId());
			AppDeployInfo a = (AppDeployInfo) appBiz.get(targetId);
			o.setCode(a.getCode());
			o.setCreateTime(Util.getStdmfDateTime());
			o.setLastTime(o.getCreateTime());
			o.setName(a.getName());
			o.setOwnerId(logon.getId());
			// TODO 支持其它变量
			o.setPackPath(a.getPackPath2());
			o.setPlanId(o.getPlanId());
			o.setTargetId(targetId);
			o.setType(BuildPlanItem.TYPE_APP);
			o.setVer(a.getVer());
			ReplyInfo<Object> ro = planAppBiz.save(o);
			if (ro.isSuccess()) {
				continue;
			}
			log.error("Error on save build plan file item, reason: {}", ro.getData());
			return ro;
		}
		return ReplyInfo.SUCCESS;
	}

	@JsonIgnoreProperties({ "insts", "libs", "svcs", "files" })
	@RequestMapping("/list.do")
	@Authorized(code = "deploy.plan.app.list")
	public ReplyInfo<Object> list(String projId, String planId, boolean in, String key, String orderBy, int pageNo,
			int pageSize) {
		PagedResult<AppDeployInfo> pr = planAppBiz.list(projId, planId, in, key, orderBy, pageNo, pageSize);
		return new ReplyInfo<Object>(true, pr);
	}
}